﻿using EFMVC.EDMX;
using EFMVC.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace EFMVC.AchieveInterface
{
    public class BaseReposity<T> : IBaseReposity<T>
        where T : class
    {
        private TPYEntities1 Context;
        internal DbSet<T> dbSet;
        public BaseReposity(TPYEntities1 dbContext)
        {
            this.Context = dbContext;
            this.dbSet = Context.Set<T>();
        }

        public IEnumerable<T> GetUsers()
        {
            return Context.Set<T>().ToList(); ;
        }
        public T GetUserByID(Guid userID)
        {

            return Context.Set<T>().Find(userID);
        }
        public void InsertUser(T user)
        {
            Context.Set<T>().Add(user);
        }
        public void DeleteUser(int userID)
        {
            T sysUser = Context.Set<T>().Find(userID);
            Context.Set<T>().Remove(sysUser);
        }
        public void UpdateUser(T user)
        {
            Context.Entry<T>(user).State = EntityState.Modified;
        }
        public void Save()
        {
            Context.SaveChanges();
        }
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public IEnumerable<T> Get(Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
         string includeProperties = "")
        {
            IQueryable<T> query = dbSet;
            if (filter != null)
            {
                query = query.Where(filter);
            }
            foreach (var item in includeProperties.Split(new char[] {','},StringSplitOptions.RemoveEmptyEntries))
            {
                query.Include(item);
            }
            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }
    }
}